import 'package:flutter/material.dart';
import 'package:flutter_common_ui/src/common_ui_config.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../other/ink_well_x.dart';

abstract class IShowText {
  String showText();
}

typedef TargetBuilder = Offset Function(
  Offset targetOffset,
  Size targetSize,
);
//模仿DropdownButton
void showPopupList<T>(
  BuildContext context, {
  String tag = "showPopupList",
  double width = 150,
  double itemHeight = 40,
  double? height,
  double dialogMaxHeight = 240,
  Alignment? alignment,
  int? maxLines,
  TextOverflow? overflow,
  List<T> data = const [],
  T? selectedItem,
  ValueChanged<T>? onChanged,
  TargetBuilder? targetBuilder,
}) {
  if (SmartDialog.checkExist(tag: tag)) return;

  Widget buildContent(BuildContext context) {
    return ListView.separated(
      shrinkWrap: true,
      itemBuilder: (context, index) {
        final item = data[index];
        final text = Text(
          item is IShowText ? item.showText() : item.toString(),
          style: selectedItem == null ? null : TextStyle(color: data.indexOf(selectedItem) == index ? Theme.of(context).primaryColor : null),
          textAlign: TextAlign.center,
          maxLines: maxLines,
          overflow: overflow,
        );
        return InkWellX(
          onTap: () {
            SmartDialog.dismiss();
            onChanged?.call(item);
          },
          child: Container(
            width: width,
            height: itemHeight,
            padding: EdgeInsets.symmetric(horizontal: 10),
            alignment: Alignment.center,
            child: text,
          ),
        );
      },
      separatorBuilder: (context, index) {
        return Divider(height: 1, color: CommonUiConfig.getPopupDividerColor());
      },
      itemCount: data.length,
    );
  }

  Widget buildEmpty(BuildContext context) {
    return SizedBox(width: width, height: itemHeight, child: Center(child: Text(CommonUiConfig.i18KeyNoData.tr)));
  }

  SmartDialog.showAttach(
    targetContext: context,
    alignment: alignment,
    tag: tag,
    usePenetrate: false,
    maskColor: Colors.transparent,
    nonAnimationTypes: [SmartNonAnimationType.maskClose_nonAnimation],
    targetBuilder: targetBuilder,
    builder: (_) {
      return Container(
        width: width,
        height: height,
        constraints: BoxConstraints(maxHeight: dialogMaxHeight, minHeight: itemHeight),
        margin: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: CommonUiConfig.getPopupBg(),
          boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 5, spreadRadius: 0.2)],
          borderRadius: BorderRadius.circular(5),
        ),
        child: data.isNotEmpty ? buildContent(context) : buildEmpty(context),
      );
    },
  );
}
